package com.gel.shortLink.service.impl;

import cn.hutool.http.HttpConnection;
import com.gel.shortLink.service.UrlTitleService;
import lombok.SneakyThrows;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;

import javax.print.DocFlavor;
import java.net.HttpURLConnection;
import java.net.URL;


@Service
public class UrlTitleServiceImpl implements UrlTitleService {
    @SneakyThrows
    @Override
    public String getTitleByUrl(String url) {
        // 创建URL对象
        URL targetUrl=new URL( url);
        //创建HttpURLConnection对象链接
        HttpURLConnection connection=(HttpURLConnection) targetUrl.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
        int responseCode = connection.getResponseCode();
        // 获取响应码
        if(responseCode==HttpURLConnection.HTTP_OK){
            // 获取网页内容
            Document document = Jsoup.connect(url).get();
            String title = document.title();
            return title;
        }
        return "Error while fetching title.";
    }
}
